package com.zzjson.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.WriteResultChecking;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.config</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月10日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
//@Configuration
public class MongoConfiguration {
    @Bean
    public MongoClient configMongoDbClient(@Value("${mongodb.host:localhost}") String host,
                                           @Value("${mongodb.port:27017}") int port,
                                           @Value("${mongodb.database:myNewCollection1}") String database,
                                           @Value("${mongodb.username:null}") String username,
                                           @Value("${mongodb.password:null}") String password) {
        ServerAddress serverAddress = new ServerAddress(host, port);

        List<MongoCredential> mongoCredentialList = new ArrayList<>();
        //MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());
        //mongoCredentialList.add(credential);
        //MongoClient mongoClient = new MongoClient(serverAddress, mongoCredentialList);
        MongoClient mongoClient = new MongoClient(serverAddress);
        return mongoClient;
    }

    @Bean("mongoDbFactory")
    public MongoDbFactory configMongoDbFactory(@Autowired MongoClient mongoClient,
                                               @Value("${mongodb.database:myNewCollection1}") String database) {
        return new SimpleMongoDbFactory(mongoClient, database);
    }

    @Bean("mongoTemplate")
    public MongoTemplate configMongoTemplate(MongoDbFactory mongoDbFactory) {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
        mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION);
        return mongoTemplate;
    }
}